﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using School.Entities;

namespace EF.WebApi.Controllers;

/// <summary>
/// 课程管理
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class CoursesController : ControllerBase {
    private readonly SchoolContext _context;

    public CoursesController (SchoolContext context) {
        _context = context;
    }

    /// <summary>
    /// 获取课程列表
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Courses>>> GetCourses () {
        return await _context.Courses.ToListAsync();
    }

/// <summary>
/// 获取课程详情
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ActionResult<Courses>> GetCourses (int id) {
        var courses = await _context.Courses.FindAsync(id);

        if (courses == null) {
            return NotFound();
        }

        return courses;
    }

/// <summary>
/// 修改课程
/// </summary>
/// <param name="id"></param>
/// <param name="courses"></param>
/// <returns></returns>
    [HttpPut("{id}")]
    public async Task<IActionResult> PutCourses (int id, Courses courses) {
        if (id != courses.Id) {
            return BadRequest();
        }

        _context.Entry(courses).State = EntityState.Modified;

        try {
            await _context.SaveChangesAsync();
        } catch (DbUpdateConcurrencyException) {
            if (!CoursesExists(id)) {
                return NotFound();
            } else {
                throw;
            }
        }

        return NoContent();
    }

    /// <summary>
    /// 添加课程
    /// </summary>
    /// <param name="courses"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ActionResult<Courses>> PostCourses (Courses courses) {
        _context.Courses.Add(courses);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetCourses", new { id = courses.Id }, courses);
    }

    /// <summary>
    /// 删除课程
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteCourses (int id) {
        var courses = await _context.Courses.FindAsync(id);
        if (courses == null) {
            return NotFound();
        }

        _context.Courses.Remove(courses);
        await _context.SaveChangesAsync();

        return NoContent();
    }

    /// <summary>
    /// 课程是否存在
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private bool CoursesExists (int id) {
        return _context.Courses.Any(e => e.Id == id);
    }
}
